package cc.catface.api.exception;

import cc.catface.common.output.BizException;
import cc.catface.common.output.ErrorCode;
import cc.catface.common.output.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常拦截
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = BizException.class)
    @ResponseBody//自定义异常
    public Result<Object> handleBizException(HttpServletRequest request, BizException e) {
        log.error("业务异常:{}", e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }

    /**
     * 空指针
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result<Object> handleNullException(HttpServletRequest request, NullPointerException e) {
        log.error("空异常:{}", e.toString());
        return Result.error(ErrorCode.ERROR_NULL);
    }

    /**
     * 请求方法不匹配
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Result<Object> handleHttpRequestMethodNotSupportedException(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
        log.error("请求方法不匹配:{}", e.toString());
        return Result.error(ErrorCode.ERROR_HTTP_REQUEST_METHOD_NOT_SUPPORTED);
    }

    /**
     * 请求参数错误
     */
    @ExceptionHandler(value = HttpMessageNotReadableException.class)
    @ResponseBody
    public Result<Object> handleHttpMessageNotReadableException(HttpServletRequest request, HttpMessageNotReadableException e) {
        log.error("请求参数异常:{}", e.toString());
        return Result.error(ErrorCode.ERROR_HTTP_MESSAGE_NOT_READABLE);
    }

    /**
     * 上传文件无文件错误
     */
    @ExceptionHandler(value = MultipartException.class)
    @ResponseBody
    public Result<Object> handleMultipartException(HttpServletRequest request, MultipartException e) {
        log.error("上传文件无文件异常:{}", e.toString());
        return Result.error(e.toString());
    }

    /**
     * 其他异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<Object> handleException(HttpServletRequest request, Exception e) {
        log.error("未知异常:{}", e.toString());
        return Result.error(ErrorCode.ERROR_INTERNAL);
    }
}
